﻿# Author: Tylor Zhang
# Email: zhangyunqiao@gmail.com


# Create your views here.
import datetime
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib import auth
from django.db.models import permalink
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from meet001.meetup.forms import \
    ProfileForm, LoginForm, RegisterForm, UserAlreadyExistsException
from meet001.meetup.models import \
    Register, UserAlreadyActivatedException, UserActivationFailedException
from meet001.meetup.group_views import add_member, create_plus_join
from django.db.models import permalink
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.contrib import auth
import urllib


ERRMSG_LOGIN_FAILED = '''用户名密码错误。请重新输入。或<a href="/accounts/register/">注册新帐户</a>。'''
ERRMSG_USER_ALREDAY_EXIST = '''该邮箱已经被注册，换一个吧！'''


@permalink
def get_absolute_url(uuid):
  return ('meetup.account_views.activate', [uuid])

def _set_remember_cookie(request, response):
  '''Set the session cookie to expire in 2 weeks'''
  max_age = settings.SESSION_COOKIE_AGE
  expires = datetime.datetime.strftime(
      datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE),
      "%a, %d-%b-%Y %H:%M:%S GMT")
  response.set_cookie(
      settings.SESSION_COOKIE_NAME, 
      request.session.session_key,
      max_age = max_age, expires = expires, 
      domain = settings.SESSION_COOKIE_DOMAIN,
      secure = settings.SESSION_COOKIE_SECURE or None)


def _handle_valid_login(request, form):
  cd = form.cleaned_data
  user = auth.authenticate(username=cd['email'], password=cd['password'])
  if user is not None and user.is_active:
    auth.login(request, user)

    #handle if group id is contained
    if 'group_id' in request.POST:
      g_id = request.POST['group_id']
      add_member(g_id, user.id)
      return HttpResponseRedirect('/group/%s' %g_id)
    
    #handle if groupname is contained
    if 'groupname' in request.POST:
      group = create_plus_join(request.POST, user)
      return HttpResponseRedirect('/group/%d' %group.id)

    # If user request for storing the cookie for next use.
    response = HttpResponseRedirect('/groups/search/')
    if cd['remember']:
      _set_remember_cookie(request, response)
    return response 
  else:
    return render_to_response(
        'meetup_new_login.html',
        {'form':form, 'failed':True, 'errmsg': ERRMSG_LOGIN_FAILED},
        context_instance=RequestContext(request))


def _login_post(request):
    form = LoginForm(request.POST)
    if form.is_valid():
      return _handle_valid_login(request, form)
    else:
      return render_to_response(
          "meetup_new_login.html", 
          {'form':form, 'failed': False},
          context_instance=RequestContext(request))

def _login_get(request):
  form = LoginForm()
  return render_to_response(
      'meetup_new_login.html',
      {'form':form, 'failed': False},
      context_instance=RequestContext(request))
  
#handle logout
def logout(request):
  #raw realization. Need to be refine.
  #This will remove the request.user, or it will cause some problems.
  auth.logout(request) 
  #redirect to a successful page.
  return HttpResponseRedirect("/accounts/login/")


def login(request):
  failed = False
  if request.method == "POST":
    return _login_post(request)
  else:
    return _login_get(request)

  # handle /register/
def register(request):
  if request.method == "POST":
    form = RegisterForm(request.POST)
    if form.is_valid():
      try:
        uuid, email = form.save()
        url = request.build_absolute_uri(
            get_absolute_url(uuid) + '?' + urllib.urlencode({'e': email}))
        print url
        return HttpResponseRedirect('/accounts/thanks/')
      except UserAlreadyExistsException:
        return render_to_response(
            "meetup_new_register.html", 
            {'form': form, 'failed': True, 'errmsg': ERRMSG_USER_ALREDAY_EXIST}, 
            context_instance=RequestContext(request))
    else:
      return render_to_response(
          "meetup_new_register.html",
          {'form': form, 'failed':False},
          context_instance=RequestContext(request)
          )
  else:
    form = RegisterForm()
    return render_to_response('meetup_new_register.html', 
        {'form': form, 'failed': False}, 
        context_instance=RequestContext(request))


# handle /thanks/
def thanks(request):
  return render_to_response('meetup_new_thanks.html', {}, context_instance=RequestContext(request))

# handle /thanks/
@login_required
def profile(request):
  if request.method == "POST":
    form = ProfileForm(request.POST, request.FILES)
    if form.is_valid():
      form.save(request.user)
  else:
    form = ProfileForm()
  first = False
  if 'first' in request.GET and request.GET['first'] == u'1':
    first = True
  return render_to_response(
      'meetup_new_profile.html', 
      {'form':form, 'first':first}, 
      context_instance=RequestContext(request))

# handle /activate/[uuid]/?e=e
# added handle /activate/[uuid]/?e=e?g_id=group_id
def activate(request, uuid):
  if 'e' in request.GET:
    e = request.GET['e']
    try:
      r = Register.activate(e, uuid)
      user = auth.authenticate(username = r.email, password = r.password)
      if user is not None and user.is_active:
        auth.login(request, user)
        return HttpResponseRedirect('/accounts/profile/?first=1')
      else:
        return HttpResponse('login failed')
    except UserActivationFailedException:
      return HttpResponse('failed activation')
    except UserAlreadyActivatedException:
      return HttpResponse('already activated!')
  else:
    return HttpResponse('failed3')
